// 重写xhr的方法
export const originalProto = XMLHttpRequest.prototype;
export const originalOpen = originalProto.open;
export const originalSend = originalProto.send;

function overwriteOpenAndSend() {
    originalProto.open = function newOpen(...args) {
        this.method = args[0];
        this.url = args[1];
        originalOpen.apply(this, args);
    }

    originalProto.send = function newSend(...args) {
        this.startTime = Date.now();
        const onLoaded = () => {
            this.endTime = Date.now();
            this.duration = this.endTime - this.startTime;
            const {
                url,
                method,
                startTime,
                duration,
                status,
                endTime
            } = this;
            const reportData = {
                url,
                method: method.toUpperCase(),
                startTime,
                duration,
                status,
                endTime,
                type: "performance",
                subType: "xhr",
                success: status >= 200 && status < 300
            }
            // 上报数据todo
            this.removeEventListener("loadend", onLoaded,true);
        }
        this.addEventListener("loadend", onLoaded,true);
        originalSend.apply(this, args);
    }
}

export default function observerXHR() {
    overwriteOpenAndSend();
}